package com.example.controller.user;


import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.easysdk.factory.Factory;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.common.Result;
import com.example.config.AliPayConfig;
import com.example.entry.OrderForm;
import com.example.entry.dto.AlipayDto;
import com.example.service.AlipayService;
import com.example.service.IOrderFormService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RequestMapping("/web/alipay")
@RestController
public class AlipayWebController {

    @Resource
    AliPayConfig aliPayConfig;

    @Resource
    private IOrderFormService orderFormService;

    @Resource
    private AlipayService alipayService;


    @GetMapping("/pay")
    public String alipayPay(AlipayDto alipayDto) {
        DefaultAlipayClient alipayClient = new DefaultAlipayClient(
                aliPayConfig.getGatewayUrl(),
                aliPayConfig.getAppId(),
                aliPayConfig.getAppPrivateKey(),
                aliPayConfig.getFormat(),
                aliPayConfig.getCharset(),
                aliPayConfig.getAlipayPublicKey(),
                aliPayConfig.getSignType()
        );

        AlipayTradePagePayRequest payRequest = new AlipayTradePagePayRequest();
        payRequest.setNotifyUrl(aliPayConfig.getNotifyUrl());
        payRequest.setReturnUrl(aliPayConfig.getReturnUrl());

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("out_trade_no", alipayDto.getOutTradeNo());
        jsonObject.put("total_amount", alipayDto.getTotalAmount());
        jsonObject.put("subject", alipayDto.getSubject());
        jsonObject.put("product_code", "FAST_INSTANT_TRADE_PAY");
        payRequest.setBizContent(jsonObject.toString());
        String form = "";
        try {
            form = alipayClient.pageExecute(payRequest).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return form;
    }

    /**
     * 支付宝回调
     *
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/notify")
    public Result payNotify(HttpServletRequest request) throws Exception {
        System.out.println("---------------进入支付回调---------------");
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("---------------支付宝异步回调---------------");
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
            }
            System.out.println(params);

            // 根据订单号查询信息
            LambdaQueryWrapper<OrderForm> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(OrderForm::getOrderNumber, params.get("out_trade_no"));
            // 获取订单信息
            OrderForm orderFormServiceOne = orderFormService.getOne(lambdaQueryWrapper);

            // 支付成功，将商品数量、用户余额进行修改，并发布到抢单表-----------------
            // 支付金额插入到数据表
            orderFormServiceOne.setProductMoney(Double.valueOf(params.get("buyer_pay_amount")));
            orderFormService.saveOrUpdate(orderFormServiceOne);
            System.out.println(orderFormServiceOne);

            alipayService.updateMessage(orderFormServiceOne);

            // 支付宝验签
            if (Factory.Payment.Common().verifyNotify(params)) {
                System.out.println("交易名称:" + params.get("subject"));
                System.out.println("交易状态:" + params.get("trade_status"));
                System.out.println("支付宝交易凭证号:" + params.get("trade_no"));
                System.out.println("商户订单号:" + params.get("out_trade_no"));
                System.out.println("交易金额:" + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id:" + params.get("buyer_id"));
                System.out.println("买家付款时间:" + params.get("gmt_payment"));
                System.out.println("买家付款金额:" + params.get("buyer_pay_amount"));
                // 验签通过
            }
        }
        return Result.error("回调错误~");
    }

}
